package com.mocoder.chatdemo.util;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 * Created by Administrator on 2018/3/10.
 */
public class ByteUtil {

    public static final byte[] HEADER_USERSCAN_REQ = str2byte("chat1");
    public static final byte[] HEADER_USERSCAN_RES = str2byte("chat2");
    public static final byte[] HEADER_CHAT_MSG_USER_REQ = str2byte("chat3");
    public static final byte[] HEADER_CHAT_MSG_ROOM_REQ = str2byte("chat4");

    public static byte[] str2byte(String str) {
        try {
            return str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static String byte2str(byte[] bytes) {
        try {
            return new String(bytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static String byte2str(byte[] bytes, int offset, int length) {
        try {
            return new String(bytes, offset, length, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static int byte2int(byte[] bytes, int offset) {
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.put(bytes, offset, 4);
        buffer.flip();
        return buffer.getInt();
    }

    public static byte[] int2byte(int value) {
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.putInt(value);
        buffer.flip();
        return buffer.array();
    }

    public static long byte2long(byte[] bytes, int offset) {
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.put(bytes, offset, 8);
        buffer.flip();
        return buffer.getLong();
    }

    public static byte[] long2byte(long value) {
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(value);
        buffer.flip();
        return buffer.array();
    }

    public static boolean equals(byte[] target, byte[] dest, int offset, int len) {
        for (int i = 0; i < target.length; i++) {
            if (target[i] != dest[offset + i]) {
                return false;
            }
        }
        return true;
    }

    public static byte[] join(byte[]... bytes) {
        int total = 0;
        for (byte[] aByte : bytes) {
            total += aByte.length;
        }
        byte[] bytes1 = new byte[total];
        int index = 0;
        for (byte[] aByte : bytes) {
            System.arraycopy(aByte, 0, bytes1, index, aByte.length);
            index += aByte.length;
        }
        return bytes1;
    }
}
